const express = require('express');
const router = express.Router();
const pdf = require("html-pdf");
const docx = require("html-docx-js");
const docx2 = require("html-to-docx");

router.post("/pdf", (req, res) => {
  if (req.body && req.body.html) {
    const html = `
    <!doctype html>
    <html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport"
              content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>${req.body.filename || "download.pdf"}</title>
        <style>html {font-size: 11px;} body {padding: 0 35px;} p, h1, h2, h3, h4, h5, h6, li {white-space: pre-wrap; margin: 0; }</style>
    </head>
    <body>
        ${req.body.html}
    </body>
    </html>
    `
    pdf.create(html, {
      format: "A4",
      header: {
        height: "30px",
      },
      footer: {
        height: "30px"
      },
    }).toBuffer((err, buffer) => {
      if (err) {
        res.status(400);
        res.end();
      } else {
        res.attachment(req.body.filename || "download.pdf")
        res.end(buffer);
      }
    });
  } else {
    res.status(400);
    res.end();
  }
})

router.post("/word", (req, res) => {
  if (req.body && req.body.html) {
    const html = `
    <!doctype html>
    <html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport"
              content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>${req.body.filename || "download.docx"}</title>
        <style>html {font-size: 12px;}  p, h1, h2, h3, h4, h5, h6, li {white-space: pre-wrap; margin: 0; }</style>
    </head>
    <body>
        ${req.body.html}
    </body>
    </html>
    `

    res.attachment(req.body.filename, "download.docx");
    res.end(docx.asBlob(html));
  } else {
    res.status(400);
    res.end();
  }
})

router.post("/word2", (req, res) => {
  if (req.body && req.body.html) {
    const html = `
    <!doctype html>
    <html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport"
              content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>${req.body.filename || "download.docx"}</title>
    </head>
    <body>
        ${req.body.html.replace(/\t{2}/g, "\t")}
    </body>
    </html>
    `

    res.attachment(req.body.filename || "download.docx");

    docx2(html).then(r => {
      res.attachment(req.body.filename || "download.docx");
      res.end(r);
    }).catch(e => {
      res.status(400);
      res.end();
    })
  } else {
    res.status(400);
    res.end();
  }
})

module.exports = router;
